package com.elontian.http.async2.util;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.elontian.application.CodeBoyApplicationInfo;
import com.elontian.http.async2.handler.AsyncHttpHandler;
import com.elontian.http.async2.modle.Response;
import com.elontian.http.async2.strategy.IAsyncStrategy;
import com.elontian.util.CheckUtil;

public class AsyncRunable implements Runnable {

	private IAsyncStrategy strategy;
	private AsyncHttpHandler handler;
	private Lock lock = new ReentrantLock();// 锁对象

	public AsyncRunable(AsyncHttpHandler handler) {
		this.handler = handler;
	}

	public void setStrategy(IAsyncStrategy strategy) {
		this.strategy = strategy;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		lock.lock();

		try {
			if (CheckUtil.isNull(strategy)) {
				handler.sendFailMessage(new NullPointerException());
			}

			Response result = strategy.getResponse();

			if (result.isHavaResult()) {
				handler.sendSuccMessage(result);
			} else {
				handler.sendFailMessage(new NullPointerException());
			}

		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			lock.unlock();
		}

	}

	public void excute() {
		// TODO Auto-generated method stub
		CodeBoyApplicationInfo.executorService.submit(this);
	}

}
